<?php

namespace App\Service\VendorClient\Shoptangyin;

use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use App\Model\PssModel\ServiceConfig;

/**
 * 唐印供应商SDK
 * @author hujian
 */
class ShoptangyinApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shoptangyin';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);

        //判断支付方式是否存在
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ?? $payCommanyCode;
        $payWayInfo     = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_PAY, $payCommanyCode, false);
        if (empty($payWayInfo)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$payCommanyCode}】未映射，请联系管理员处理");
        }
        //获取下单商品信息
        $palceOrderGoods    = [];
        $totalGoodsMoney    = '0.00';
        $goodsTotalMoney    = '0.00';
        $goodsTotalMoneyNot = '0.00';
        $wayTaxFee          = '0.00';
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;
            if ($key == 0) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money, (string)$quantity, 3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney, (string)100, 1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100, 2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney, 2);
            }
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);
            
            //含税税率
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            //不含税价格
            $not_tax_price      = bcdiv((string)$singleGoodsPrice, (string)$tax_rate,3);
            //echo "含税单价:".$singleGoodsPrice."含税税率:".$tax_rate."不含税价格：".$not_tax_price;
            $not_tax_price      = ceil(bcmul((string)$not_tax_price,(string)'100',1));
            // echo "含税税率:".$tax_rate."不含税价格：".$not_tax_price;
            $not_tax_price      = bcdiv((string)$not_tax_price,'100',2);
            
            //不含税总价
            $goodsTotalPrice    = bcmul((string)$not_tax_price, (string)$buyAcount, 2);
            
            //税金
            $singleGoodsTax     = bcsub((string)$singleGoodsPrice, (string)$not_tax_price,3);
            $taxAll             = bcmul((string)$singleGoodsTax, (string)$buyAcount, 2);
            //不含税总金额
            $goodsTotalMoneyNot = bcadd((string)$goodsTotalMoneyNot, (string)$goodsTotalPrice, 2);
            //含税总金额
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, (string)$totalGoods, 2);
            //总税费
            $wayTaxFee = bcadd((string)$wayTaxFee, (string)$taxAll, 2);
            //下单商品组
            $goodsInfo         = [
                'SKUID'       => $item['supplier_skucode'],//商品编码 订单内必须唯一
                'SKUNAME'     => $item['goods_name'],//商品名称
                'SUPPLIERSKU' => $item['supplier_skucode'],//备案料号
                'QTY'         => (int)$buyAcount,//数量
                'TAXEDPRICE'  => $singleGoodsPrice,//含税价
                'NOTAXPRICE'  => $not_tax_price,//未含税价
                'SINGLETAX'   => $singleGoodsTax,//单个商品税款，不用乘以数量
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        $couponFee    = $goodsTotalMoney > $orderInfo['real_total_money'] ? bcsub($goodsTotalMoney, $orderInfo['real_total_money'], 2) : '0.00';
        $requestParam = [
            'ORDERNO'               => $order_sn,//订单号，唯一性不可重复
            'GMORDERNO'             => $order_sn,//海关单号，发到海关的支付支付单号，后续出库以此为单号
            'PAYTYPE'               => (string)$payWayInfo['service_third_value'],//支付方式
            'PAYORDERID'            => $order['paySerial'] ?? $apply_extends['paySerial'],//支付交易流水号
            'BUYTIME'               => $order_time,//下单时间
            'PAYTIME'               => $pay_time,//支付时间
            'RECEIVER_ID_NO'        => $orderInfo['buyer_idcard'],//购买人身份证号,//收件人身份证
            'RECEIVER_NAME'         => $orderInfo['receive_name'],//收件人
            'RECEIVER_PROVINCE'     => $orderInfo['province'],//收件省份
            'RECEIVER_CITY'         => $orderInfo['city'],//收件城市
            'RECEIVER_DISTRICT'     => $orderInfo['district'],//收件区域
            'RECEIVER_TEL'          => $orderInfo['recveive_phone'],//收件人电话
            'RECEIVER_SHORTADDRESS' => $orderInfo['receive_address'],//收件地址
            'BUYER_NAME'            => $orderInfo['buyer_realname'],//订购人
            'BUYER_ID_TYPE'         => '1',//1 身份证
            'BUYER_ID'              => $orderInfo['buyer_idcard'],//1 订购证件号码
            'GOODS_FEE'             => $goodsTotalMoneyNot,//货物总值 不含税
            'TAX_FEE'               => $wayTaxFee,//税款
            'TRANSPORT_FEE'         => '0.00',//运费
            'INSURED_FEE'           => '0.00',//保价费
            'DISCOUNT'              => $couponFee,//折扣 大于等于0
            'ACTUAL_PAID'           => $orderInfo['real_total_money'],//实际支付 货物总值+税款+运费+保价费-折扣=实际支付
            'EBPCODE'               => $order['enterpriseNum'] ?? $apply_extends['enterpriseNum'],//电商平台代码
            'EBPNAME'               => $order['enterpriseName'] ?? $apply_extends['enterpriseName'],//电商平台名称

            'ESHOP_ENT_CODE' => $this->config['eshop_ent_code'] ?? '',//电商企业代码
            // 'MALL_ID' => '0.00',// 拼多多店铺ID
            'ESHOP_ENT_NAME' => $this->config['eshop_ent_name'] ?? '',// 电商企业名称
            'SKUITEMS'       => $palceOrderGoods,//商品明细
        ];
        $data         = [
            'method' => 'createOrder',
            'data'   => [
                'IDCODE' => $this->config['idcode'],
                'ORDERS' => [$requestParam]
            ],
        ];
        return $this->execute($data);
    }
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] )
    {

        $requestParam= [[
            'ORDERNUM'     => $params['supplierOrder']['supplier_dsn'],
            'PLATFORM'     => 'GMORDER',
            'REASON'       => $params['order']['exceptReason'] ?? '申请订单退款作废,不要了',
        ]];
        $data         = [
            'method' => 'cancelOrder',
            'data'   => [
                'IDCODE' => $this->config['idcode'],
                'ORDERS' => $requestParam
            ],
        ];
        return $this->execute($data);
    }
    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        if (!isset($this->config[$param['method']])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config['baseurl'];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $pushData  = [
            'me'   => $this->config[$param['method']],
            'data' => json_encode($param['data'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        ];
        $parameter = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [
                    'Content-Type: application/x-www-form-urlencoded'
                ],
            ],
        ];
        $resTask   = TaskWorker::instance()->addTask($parameter);
        $resTask   = current($resTask);
        $result    = @json_decode($resTask['response']['result'], true);
        if (isset($result['RESULTCODE']) && $result['RESULTCODE'] == 0) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $result['RESULTMESSAGE'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
    }
}